<?php
    // php api接口原理

    // 1.设计数据库

    // 2.链接数据库
    $conn=new mysqli("localhost","root","123456","api");
    if($conn->connect_error){
        die("Could not connect to datebase!");
    }
    // 3.构建接口
    $action="read";

    // 返回数据对象
    $res = array('error' => false);

    $id=$_POST['id'];
    $name=$_POST['name'];
    $password=$_POST['password'];
    $conn->query("set names utf8");

    if(isset($_GET['action'])){
        $action= $_GET['action'];
    }

    // 获取数据接口
    if($action=="read"){
        $result = $conn->query("SELECT * FROM `api_user`");
        // var_dump($result);
        $users=array();
        while($row = $result->fetch_assoc()){
            array_push($users,$row);
        }
        // var_dump($users);
        $res['users'] = $users;
    }

    // 增加数据
    if($action=="create"){
        $result= $conn->query("INSERT INTO `api_user` (`name`,`password`) VALUES ('$name','$password')");
        if($result){
            $res['message'] = "success!";
        }else{
            $res['error'] = true;
            $res['message'] = "failed!";
        }
    }

    // 更新数据
    if($action=="update"){
        $result=$conn->query("UPDATE `api_user` SET `name`='$name',`password`='$password' WHERE `id` = '$id' ");
        if($result){
            $res['message'] = "success!";
        }else{
            $res['error'] = true;
            $res['message'] = "failed!";
        }
    }

    // 删除数据
    if($action=="delete"){
        $result=$conn->query("DELETE FROM `api_user` WHERE `id` = '$id' ");
        if($result){
            $res['message'] = "success!";
        }else{
            $res['error'] = true;
            $res['message'] = "failed!";
        }
    }

    $conn->close();

    header("Content-type:application/json");
    // 返回数据
    echo json_encode($res);
    die();
?>